package io.gitee.hefren.hhsharding.strategy.impl;

import groovy.lang.Closure;
import io.gitee.hefren.hhsharding.strategy.HhShardingStrategy;
import io.gitee.hefren.hhsharding.utils.InlineExpressionParser;

import java.util.List;
import java.util.Map;

/**
 * @Date 2024/8/21
 * @Author lifei
 */
public class HhHashShardingStrategy implements HhShardingStrategy {

    private final String shardingColumns;
    private final String shardingStrategy;

    public HhHashShardingStrategy(String shardingColumns, String shardingStrategy) {
        this.shardingColumns = shardingColumns;
        this.shardingStrategy = shardingStrategy;
    }

    @Override
    public List<String> getShardingColumns() {
        return List.of(shardingColumns);
    }

    @Override
    public String doSharding(Map<String, Object> shardingParams) {
        String expression = InlineExpressionParser.handleClosureExpression(shardingStrategy);
        InlineExpressionParser parser = new InlineExpressionParser(expression);
        Closure<?> closure = parser.evaluateInlineExpression();
        closure.setProperty(shardingColumns, shardingParams.get(shardingColumns));
        return closure.call().toString();
    }
}
